package com.example.demo.interceptor;

import java.util.ArrayList;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    public static ArrayList<Integer> list= new ArrayList<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        // 解决跨域
        if (request.getMethod().equals("OPTIONS")) {
//             response.setStatus(200);
//             response.getWriter().println("{\"code\":200}");
            return false;
        }
        if (token==null||!request.getRequestURI().equals("/login")&&!list.contains(Integer.parseInt(token))) {
            response.getWriter().println("{\"code\":403,\"msg\":\"token错误\"}");
            return false;
        }
        // response.setHeader("Access-Control-Allow-Methods", "*");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 在控制器处理完请求后但尚未渲染视图时执行的操作
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在请求完成并且视图已经渲染之后执行的操作
    }
}
